package code.example.base.util.concurrent.lock.memory.visval;

import code.example.base.util.concurrent.lock.Counter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
 *   不使用锁，计算结果<10000,原因：内存不可见，引起的线程安全问题
 *
 */
public class TestMemoryVisible1 {
    Counter counter = new Counter();
    ReentrantLock lock = new ReentrantLock();
    public  void addCount(){

        for (int i = 0; i < 1000; i++) {
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            }catch (Exception e){}

            lock.lock();
            try {
                int count = counter.getCount();
                int newCount = count + 1;
                System.out.println("" + Thread.currentThread().getName() + ":" + newCount);
                counter.setCount(newCount);
            }finally {
                lock.unlock();
            }
        }
    }


    public void test(){
        ExecutorService executorService = Executors.newFixedThreadPool(11);
        for(int i=0;i<10;i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                        addCount();
                    }

            });
        }


        try {
            executorService.shutdown();
            executorService.awaitTermination(100, TimeUnit.SECONDS);
        }catch (Exception e){

        }
        System.out.println(counter.getCount());
    }

    public static void main(String args []){
        new TestMemoryVisible1().test();
    }
}
